
import { useEffect, useRef, useState } from 'react'
import BScroll from '@better-scroll/core'
import PullDown from '@better-scroll/pull-down'
import Pullup from '@better-scroll/pull-up'
import './index.scss'

BScroll.use(PullDown)
// BScroll.use(Pullup)
function BetterScroll(props) {
    const wrapper = useRef(null)
    // didmount  实例化
    useEffect(() => {
        window.onload = () => {
            console.log('1111 ')
            const bs = new BScroll(wrapper.current, {
                // scrollX: false,  // 关闭横向滚动
                click: true,  // better-scroll 默认会阻止浏览器的原生 click 事件
                scrollY: true, //开启竖向滚动
                // useTransition: false,
                // eventPassthrough: 'vertical',
                bounceTime: 800,
                // pullUpLoad: true,
                pullDownRefresh: {
                    threshold: 70,
                    stop: 56
                }
            })
            bs.on('pullingDown', () => pullingDown(bs))
            // bs.on('pullingUp', () => pullingUpHandler(bs))
        }
     
    }, [])
    // 下拉刷新
    const [tips, setTips] = useState('下拉开始')
    const [isPullingDown, setIsPullingDown] = useState(false) // 是否在下拉中
    let timer = null // 定时器节流
    const pullingDown =  async(bscroll) => {
        console.log(1)
        if(timer) {
            clearTimeout(timer)
            timer = null
            return
        }
        if(!isPullingDown) {
            setTips('下拉中')
            setIsPullingDown(true)
            await props.DownloadData()
            setTips('loading')
            timer = setTimeout(() => {
                pullingDownHandler(bscroll)
                clearTimeout(timer)
                timer = null
            }, 1000)
        }
    }
    const pullingDownHandler = (bscroll) => {
        bscroll.finishPullDown()
        bscroll.refresh()
        setIsPullingDown(false)
        setTips('下拉结束')
        setTimeout(() => {
          setTips('下拉开始')
        },1000)
    }
    // 上拉加载
    const pullingUpHandler = (bs) => {
        console.log(1)
        bs.finishPullUp()
        bs.refresh()
    }
    return (
        <div ref={wrapper} className="better-Scroll">
            {/* <div className="Better-Scroll-wrapper">
                <div className="pulldown-wrapper">
                    <div className="tc pulldown-wrapper-loading">
                        {tips}
                    </div>
                </div>
            </div> */}
            {props.children}
        </div>
    )
}
export default BetterScroll
